import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import TablePage from "@/components/TablePage/TablePage";
import { tablesInterface } from "@/common/interface/table.interface";
import UserService from "./index.service";
import to from "await-to-js";
import { message, Modal } from "ant-design-vue";
import { useRouter } from "vue-router";
import Add from "./Add/Add";
import styles from "./index.module.less";
const StatusSwitch = defineComponent({
  props: {
    record: {
      type: Object,
    },
    value: {
      type: String,
    }
  },
  emits: ["change"],
  setup(props: any, { emit }) {
    const userService = new UserService();
    const loading = ref(false);
    const statusChange = async (e) => {
      loading.value = true;
      const [err, res]: any = await to(userService.statusChange({
        userId: props.record.userId,
        status: e,
      }));
      if (!err) {
        e === 0 ? message.success("开启成功!") : message.success("关闭成功!");
        emit("change");
      }
      loading.value = false;
    }
    return () => <a-switch disabled={props.record.admin} loading={loading.value} checked={props.value} checkedValue={"0"} unCheckedValue={"1"} onChange={(e) => { statusChange(e) }} />
  }
})

export default defineComponent({
  name: "Role",
  setup() {
    const router = useRouter();
    const tablePageRef = ref(null as any);
    const userService = new UserService();
    const temp = reactive({
      password: null,
    })
    // 表格定义
    const tables = reactive({
      list: [
        {
          title: "用户管理",
          rowKey: "userId",
          columns: [
            {
              title: "ID",
              dataIndex: "userId",
              align: "center",
              width: "80px",
            },
            {
              title: "用户名称",
              dataIndex: "userName",
              align: "center",
              width: "180px",
            },
            {
              title: "用户昵称",
              dataIndex: "nickName",
              align: "center",
              width: "180px",
            },
            {
              title: "手机号码",
              dataIndex: "phonenumber",
              align: "center",
              width: "180px",
            },
            {
              title: "状态",
              dataIndex: "status",
              align: "center",
              width: "180px",
            },
            {
              title: "创建时间",
              dataIndex: "createTime",
              align: "center",
              width: "240px",
            },
          ],
          toolbar: {
            left: ["refresh", "add"],
            right: ["filter", "search"],
            add: {
              permissions: "system:user:add",
              handler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'add' });
              }
            },
          },
          searchForm: {
            userName: {
              type: "input",
              label: "用户名称",
              attrs: { placeholder: "用户名称", allowClear: true },
            },
            phonenumber: {
              type: "input",
              label: "手机号码",
              attrs: { placeholder: "手机号码", allowClear: true },
            },
            status: {
              type: "select",
              label: "状态",
              attrs: { placeholder: "状态", allowClear: true },
              datas: [{ label: '开启', value: "0" }, { label: "关闭", value: "1" }],
            },
          },
          service: userService,
          operation: ({ record }) => [
            {
              type: "edit",
              permissions: "system:user:edit",
              hidden: record.admin,
              clickHandler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'edit', userId: record.userId });
              }
            },
            {
              type: "delete",
              permissions: "system:user:remove",
              hidden: record.admin,
              clickHandler: "delete",
            },
            {
              type: "custom",
              permissions: "system:user:resetPwd",
              hidden: record.admin,
              el: () => <a-button type="primary" size="small">修改密码</a-button>,
              clickHandler: () => {
                Modal.confirm({
                  title: '提示',
                  content: () => (
                    <div class={styles.signRow}>
                      <div class={styles.signRowLabel}>请输入{record.userName}的新密码</div>
                      <div class={styles.signRowValue}>
                        <input v-model={temp.password} />
                      </div>
                    </div>
                  ),
                  onOk: async () => {
                    if (!temp.password) {
                      message.error("请输入新密码!");
                      return;
                    }
                    const [err,res] = await to(userService.passwordChange({userId: record.userId, password: temp.password}));
                    if(!err) {
                      message.success("密码修改成功");
                    }
                    temp.password = null;
                  },
                  onCancel: () => {
                    temp.password = null;
                  }
                })
              }
            }
          ],
          bodyCell: ({ text, record, index, column }) => {
            if (column.dataIndex === "status") {
              return <>
                <StatusSwitch record={record} value={text} onChange={() => {tablePageRef.value.reload()}}/>
              </>
            }
          },
          popups: [
            {
              ref: "addRef",
              dom: () => <Add onChange={() => { tablePageRef.value.reload() }} />,
            },
          ],
          pagination: true,
          tableSourceFormat: {
            data: 'rows',
            pageSize: 'pageSize',
            current: 'pageNum',
          },
        }
      ],
    } as tablesInterface)
    // 配置项
    const config = reactive({
      table: tables.list[0],
    })
    return () => (
      <TablePage ref={tablePageRef} config={config} />
    )
  }
})